// 处理图片上传的接口 (一张图) 测试
let express = require('express')
//上传图片的包
let multer = require('multer')
let fs = require('fs')
let path = require('path')
let router = express.Router()
const config = require('../../config/baseinfo')
const HostUrl = `${config.PROTOCOL}://${config.HOST}:${config.PORT}`
// 引入jwt token工具
const JwtUtil = require('../../utils/jwt')
const { v4: uuidv4 } = require('uuid')
const db = require('../../config/db')


var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./public/upload/")
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + "-" + file.originalname)
    }
})

var createFolder = function (folder) {
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
}
var uploadFolder = './public/upload/';
createFolder(uploadFolder);
var upload = multer({
    storage: storage
});

router.post('/img', upload.single('file '), function (req, res, next) {
    var file = req.file;
    console.log('文件类型:%s ', file.mimetype);
    console.log('原始文件名:%s ', file.originalname);
    console.log('文件大小:%s ', file.size);
    console.log('文件保存路径:%s ', file.path);
    res.json({
        res_code: '0',
        name: file.originalname,
        url: file.path
    });
});

//上传默认头像
router.post('/default', upload.single('photo'), function (req, res) {
    // 接收前端的标题
    let name2 = req.body.name
    // 接收前端的文件
    let file = req.file
    // 定义存在在服务器的图片的路径（存在数据库的路径）
    let image = `${HostUrl}/static/upload/${file.filename}`
    // 请求需要进行token校验 
    let token = req.body.token
    let jwt = new JwtUtil(token)
    let result = jwt.verifyToken()
    let uid = uuidv4()
    let description = req.body.description
    let position = req.body.position
    let url = req.body.url
    let createdAt = req.body.createdAt
    let updatedAt = req.body.updatedAt
    let version = req.body.version
    if (result == 'err') {
        res.send({
            code: -1,
            msg: '登录已过期,请重新登录'
        })
    } else {
        //处理提交的数据
        let advert_insert_sql = "insert into default_image(uid,name,description,position,image,url,createdAt,updatedAt,version) values('" + uid + "','" + name2 + "','" + description + "','" + position + "','" + image + "','" + url + "','" + createdAt + "','" + updatedAt + "','" + version + "')"
        db.query(advert_insert_sql, function (err, rows) {
            if (err) {
                console.log(err)
            } else {
                res.send({
                    code: 200,
                    msg: '添加广告成功',
                    image
                })
            }
        })
    }
})

module.exports = router;